<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐播放</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(180deg, #fff8e1 0%, #e8f5e9 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
        }
        .navbar {
            background-color: rgba(51, 51, 51, 0.95);
            overflow: hidden;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .navbar a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
            transition: all 0.3s;
        }
        .navbar a:hover {
            background-color: rgba(221, 221, 221, 0.9);
            color: black;
        }
        .navbar a.active {
            background-color: #4CAF50;
        }
        h1 {
            color: #333;
            margin-bottom: 30px;
            text-align: left;
        }
        .header-actions {
            margin: 20px 0;
            text-align: right;
        }
        .header-actions button {
            margin-left: 10px;
            padding: 8px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .header-actions button:hover {
            background-color: #45a049;
        }
        .header-actions button:last-child {
            background-color: #f44336;
        }
        .header-actions button:last-child:hover {
            background-color: #d32f2f;
        }
        .player-controls {
            background-color: rgba(45, 45, 48, 0.95);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 100;
            color: white;
        }
        .now-playing {
            color: #66bb6a;
            font-size: 14px;
            margin-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            min-height: 20px;
            height: 20px;
            line-height: 20px;
            display: flex;
            align-items: center;
        }
        .now-playing i {
            margin-right: 5px;
        }
        .now-playing span {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            height: 20px;
            line-height: 20px;
        }
        .player-controls .progress-bar {
            width: 100%;
            height: 5px;
            background-color: rgba(255, 255, 255, 0.15);
            border-radius: 3px;
            margin: 10px 0;
            cursor: pointer;
            position: relative;
        }
        .player-controls .progress {
            width: 0%;
            height: 100%;
            background-color: #4CAF50;
            border-radius: 3px;
            transition: width 0.1s linear;
            position: relative;
            box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
        }
        .controls {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: space-between;
        }
        .control-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .upload-group {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        /* 旧的按钮样式已移除，使用.btn类统一样式 */
        
        /* 基础按钮样式 */
        .btn {
            height: 32px;
            font-size: 14px;
            padding: 0 15px;
            background-color: #64b5f6; /* 淡蓝色 */
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            color: white; /* 白色文字 */
            min-width: 80px;
        }
        .btn:hover {
            background-color: #42a5f5; /* 深一点的蓝色 */
            transform: translateY(-1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .btn i {
            margin-right: 5px;
            font-size: 14px;
        }

        /* 按钮颜色变体 */
        .play-btn {
            background-color: #4CAF50;
            color: white;
        }
        .play-btn:hover {
            background-color: #45a049;
        }

        .pause-btn {
            background-color: #ff9800;
            color: white;
        }
        .pause-btn:hover {
            background-color: #f57c00;
        }

        .stop-btn {
            background-color: #f44336;
            color: white;
        }
        .stop-btn:hover {
            background-color: #d32f2f;
        }
        .upload-btn {
            background-color: #64b5f6; /* 与其他按钮一致的淡蓝色 */
            color: white;
        }
        .upload-btn:hover {
            background-color: #42a5f5; /* 与其他按钮一致的hover效果 */
        }
        .upload-btn input[type="file"] {
            display: none;
        }
        .upload-btn i {
            font-size: 16px;
        }
        .upload-status {
            color: #666;
            font-size: 14px;
            margin-left: 10px;
        }
        .time-display {
            font-family: monospace;
            margin-left: 10px;
            color: rgba(255, 255, 255, 0.7);
        }
        .audio-list-container {
            flex: 1;
            overflow-y: auto;
            margin-bottom: 20px;
            display: flex;
            gap: 20px;
            position: relative;
        }
        .audio-list {
            background-color: rgba(240, 240, 240, 0.5);
            border-radius: 5px;
            padding: 15px;
            flex: 5;
            border: 1px solid rgba(0, 0, 0, 0.1);
            margin-right: 20px;
        }
        .playlist-container {
            flex: 3;
            background-color: rgba(240, 240, 240, 0.5);
            border-radius: 5px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            border: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        /* 文件列表样式 */
        .file-list-header {
            display: flex;
            flex-direction: column;
            margin-bottom: 15px;
            padding: 0;
            border-bottom: 1px solid rgba(0,0,0,0.1);
            background: transparent;
            border-radius: 0;
            border: none;
        }
        .file-list-title-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            padding-bottom: 8px;
            padding-top: 0;
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        .file-list-title {
            font-weight: bold;
            color: #333;
            font-size: 18px;
        }
        .file-info {
            margin: 0 0 10px 0;
            padding: 0;
        }
        .file-stats {
            margin: 10px 0 0 0;
            padding: 5px 0;
            color: #666;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: nowrap;
        }
        .file-list-actions {
            display: flex;
            gap: 10px;
        }
        
        /* 播放列表样式 */
        .playlist {
            flex: 1;
            overflow-y: auto;
        }
        .playlist-item {
            padding: 8px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .playlist-item:hover {
            background-color: rgba(0,0,0,0.05);
        }
        .playlist-item.active {
            background-color: rgba(76, 175, 80, 0.1);
            border-left: 3px solid #4CAF50;
        }
        .playlist-item .play-icon {
            width: 32px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            border: none;
            background: none;
            transition: all 0.3s;
            margin-left: 5px;
            color: #bbbbbb; /* 默认灰色 */
        }
        .playlist-item .play-icon.playing {
            color: #4CAF50; /* 播放中淡绿色 */
        }
        .playlist-item .play-icon.paused {
            color: #ffc107; /* 暂停中淡黄色 */
        }
        .playlist-item .playlist-filename {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 0 10px;
        }
        .playlist-empty {
            padding: 20px;
            color: #999;
            text-align: center;
            font-style: italic;
        }
        .path-info {
            margin: 0;
            padding: 5px 0;
            color: #666;
            font-family: monospace;
            word-break: break-all;
            font-size: 14px;
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            padding: 10px 0;
        }
        .stats-left {
            flex: 1;
            white-space: nowrap;
            padding-right: 10px;
        }
        .delete-hint {
            color: #999;
            margin-left: 5px;
            font-size: 0.85em;
            font-style: italic;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-left: auto;
        }
        /* 按钮样式统一 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            width: 400px;
            max-width: 90%;
        }
        .modal-content h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 18px;
            text-align: center;
            font-weight: bold;
        }
        .progress-container {
            margin-top: 20px;
        }
        /* 上传进度条样式 */
        .modal .progress-bar {
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        .modal .progress {
            width: 0;
            height: 100%;
            background-color: #4CAF50;
            transition: width 0.3s ease;
        }
        .progress-text {
            display: flex;
            justify-content: space-between;
            color: #666;
            font-size: 14px;
        }
        .modal-content.success {
            border-left: 5px solid #4CAF50;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        .modal-content.error {
            border-left: 5px solid #f44336;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        .upload-summary {
            margin-top: 15px;
            padding: 10px;
            background-color: #e8f5e9;
            border-radius: 5px;
            color: #2e7d32;
            font-size: 14px;
        }
        .upload-refresh-tip {
            margin-top: 10px;
            font-size: 13px;
            color: #757575;
            font-style: italic;
            text-align: center;
        }
        .modal-footer {
            margin-top: 20px;
            text-align: center;
        }
        .btn-small {
            padding: 3px 8px;
            background-color: #64b5f6; /* 淡蓝色，与其他按钮一致 */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .btn-small:hover {
            background-color: #42a5f5; /* 深一点的蓝色，与其他按钮一致 */
            transform: translateY(-1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .file-list-title-group {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .storage-info {
            color: #666;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .storage-info.warning {
            color: #ffc107;
        }
        .storage-info.danger {
            color: #ff4444;
        }
        .storage-info i {
            font-size: 16px;
        }
        .audio-item {
            display: flex;
            align-items: center;
            padding: 8px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            transition: background-color 0.2s;
        }
        .audio-item:hover {
            background-color: rgba(0,0,0,0.03);
        }
        .audio-item:last-child {
            border-bottom: none;
        }
        .audio-item input[type="checkbox"] {
            margin-left: 5px;
            margin-right: 8px;
            width: 16px;
            height: 16px;
        }
        .audio-item .filename {
            flex: 1;
            color: #333;
            padding: 0 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .audio-item .file-size {
            width: 85px;
            color: #666;
            text-align: right;
            padding-right: 10px;
            white-space: nowrap;
            font-size: 12px;
        }

        /* 区分播放列表项和文件列表项的样式 */
        #message {
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 5px;
            display: none;
        }
        #message.success {
            background-color: #e8f5e9;
            color: #2e7d32;
            border-left: 4px solid #4caf50;
        }
        #message.error {
            background-color: #ffebee;
            color: #c62828;
            border-left: 4px solid #f44336;
        }
        .audio-item .play-file-btn, .audio-item .delete-btn {
            width: 32px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            border: none;
            background: none;
            cursor: pointer;
            transition: all 0.3s;
            margin: 0 3px;
        }
        .audio-item .play-file-btn {
            color: #64b5f6; /* 淡蓝色，与其他按钮一致 */
            margin-right: 0;
        }
        .audio-item .play-file-btn:hover {
            background-color: rgba(100, 181, 246, 0.1); /* 对应淡蓝色的hover效果 */
        }
        .audio-item .delete-btn {
            color: #f44336;
        }
        .audio-item .delete-btn:hover {
            background-color: rgba(244, 67, 54, 0.1);
        }
        .playlist-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        .playlist-title {
            font-weight: bold;
            color: #333;
            font-size: 18px;
        }
        .playlist-actions {
            display: flex;
            gap: 5px;
        }

        /* 修改播放列表按钮样式 */
        .playlist-item .remove-btn {
            color: #64b5f6;
            width: 32px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            border: none;
            background: none;
            cursor: pointer;
            transition: all 0.3s;
            margin-left: 5px;
            margin-right: 0;
        }
        
        .playlist-item .remove-btn:hover {
            background-color: rgba(100, 181, 246, 0.1);
        }

        /* 不可用按钮样式 */
        .audio-item .disabled-btn {
            opacity: 0.5;
            cursor: not-allowed;
            color: #999 !important;
        }
        .audio-item .disabled-btn:hover {
            background-color: transparent !important;
            transform: none !important;
        }
        
        /* 按钮通用样式 */
        .add-to-playlist-btn {
            white-space: nowrap;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="navbar">
        <a href="/welcome.html">首页</a>
        <a href="/monitor.html">监控</a>
        <a href="/config.html" id="configLink" style="display: none;">配置</a>
        <a href="/log.html">日志</a>
        <a href="/music.html" class="active">音乐</a>
    </div>
    
    <div class="container">
        <h1>音乐播放</h1>
        
        <div id="message"></div>
        
        <div class="player-controls">
            <div class="now-playing">
                <i class="fas fa-music"></i>
                <span id="nowPlaying">未播放</span>
            </div>
            <div class="progress-bar">
                <div class="progress" id="progress"></div>
            </div>
            <div class="controls">
                <div class="control-group">
                    <button id="playBtn" class="btn play-btn">
                        <i class="fas fa-play"></i>
                        播放
                    </button>
                    <button id="pauseBtn" class="btn pause-btn" style="display: none;">
                        <i class="fas fa-pause"></i>
                        暂停
                    </button>
                    <button id="stopBtn" class="btn stop-btn">
                        <i class="fas fa-stop"></i>
                        停止
                    </button>
                    <span class="time-display" id="timeDisplay">00:00 / 00:00</span>
                </div>
            </div>
        </div>

        <div class="audio-list-container">
            <div class="playlist-container">
                <div class="playlist-header">
                    <span class="playlist-title">播放列表</span>
                    <div class="playlist-actions">
                        <button id="clearPlaylistBtn" class="btn delete-all-btn">
                            <i class="fas fa-trash-alt"></i>
                            清空
                        </button>
                    </div>
                </div>
                <div class="playlist" id="playlist">
                    <!-- 播放列表将由JavaScript动态加载 -->
                    <div class="playlist-empty">播放列表为空</div>
                </div>
            </div>
            <div class="audio-list">
                <div class="file-list-header">
                    <div class="file-list-title-row">
                        <div class="file-list-title-group">
                            <span class="file-list-title">文件列表</span>
                            <span class="storage-info">
                                <i class="fas fa-hdd"></i>
                                <span id="storageInfo">10.09 MB/1 GB</span>
                            </span>
                        </div>
                        <div class="file-list-actions">
                            <button id="addToPlaylistBtn" class="btn add-to-playlist-btn" style="display: none;">
                                <i class="fas fa-plus"></i>
                                添加选中
                            </button>
                            <label for="fileUpload" class="btn upload-btn">
                                <i class="fas fa-file-upload"></i>
                                上传文件
                                <input type="file" id="fileUpload" multiple accept="audio/*">
                            </label>
                            <button id="deleteAllBtn" class="btn delete-all-btn">
                                <i class="fas fa-trash"></i>
                                全部删除
                            </button>
                            <button id="refreshBtn" class="btn refresh-btn">
                                <i class="fas fa-sync-alt"></i>
                                刷新列表
                            </button>
                        </div>
                    </div>
                </div>
                <div id="fileList">
                    <!-- 音频列表将由JavaScript动态加载 -->
                </div>
            </div>
        </div>

        <!-- 上传进度弹框 -->
        <div id="uploadModal" class="modal">
            <div class="modal-content">
                <h3 id="uploadTitle">文件上传中</h3>
                <div class="progress-container">
                    <div class="progress-bar">
                        <div id="uploadProgress" class="progress"></div>
                    </div>
                    <div class="progress-text">
                        <span id="uploadStatus">准备上传...</span>
                        <span id="uploadPercent">0%</span>
                    </div>
                </div>
                <div id="uploadSummary" class="upload-summary" style="display: none;"></div>
                <div id="uploadRefreshTip" class="upload-refresh-tip" style="display: none;">
                    若文件未显示，请点击"刷新列表"按钮
                </div>
                <div class="modal-footer" style="display: none;" id="uploadModalFooter">
                    <button class="btn" id="uploadCloseBtn">关闭</button>
                </div>
            </div>
        </div>
        
        <!-- 提示弹框 -->
        <div id="alertModal" class="modal">
            <div class="modal-content">
                <h3 id="alertTitle">提示</h3>
                <p id="alertMessage"></p>
                <div style="text-align: center; margin-top: 20px;">
                    <button id="alertConfirmBtn" class="btn">确定</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 显示提示弹框
        function showAlert(title, message, callback) {
            const modal = document.getElementById('alertModal');
            const titleElement = document.getElementById('alertTitle');
            const messageElement = document.getElementById('alertMessage');
            const confirmBtn = document.getElementById('alertConfirmBtn');
            
            titleElement.textContent = title || '提示';
            messageElement.textContent = message;
            
            // 显示模态框
            modal.style.display = 'flex';
            
            // 设置确定按钮事件
            confirmBtn.onclick = function() {
                modal.style.display = 'none';
                if (typeof callback === 'function') {
                    callback();
                }
            };
        }
        
        // 删除音频文件
        function deleteFile(filename) {
            // 检查文件是否在播放列表中
            const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            if (playlist.includes(filename)) {
                showAlert('操作提示', '此文件在播放列表中，请先从播放列表中删除');
                return;
            }
            
            if (!confirm('确定要删除此文件吗？')) {
                return;
            }
            
            // 添加超时处理
            const timeoutPromise = new Promise((_, reject) => {
                setTimeout(() => reject(new Error('请求超时')), 5000);
            });
            
            // 实际的删除请求
            const fetchPromise = fetch(`/api/music/delete?filename=${encodeURIComponent(filename)}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.text().then(text => {
                    try {
                        return text ? JSON.parse(text) : {};
                    } catch (error) {
                        throw new Error('服务器响应格式错误');
                    }
                });
            });
            
            // 使用Promise.race来处理超时
            Promise.race([fetchPromise, timeoutPromise])
            .then(data => {
                if (data.success) {
                    setTimeout(() => {
                        loadFileList();
                    }, 500);
                } else {
                    showAlert('操作提示', data.error || '删除失败');
                }
            })
            .catch(error => {
                showAlert('操作提示', '删除文件失败: ' + error.message);
                // 即使出错也尝试刷新列表
                setTimeout(() => {
                    loadFileList();
                }, 1000);
            });
        }

        // SSE事件连接，获取实时播放状态
        let eventSource = null;

        function connectEventSource() {
            if (eventSource) {
                eventSource.close();
            }
            
            eventSource = new EventSource('/api/music/events');
            
            eventSource.addEventListener('message', function(event) {
                try {
                    const status = JSON.parse(event.data);
                    // 更新播放状态显示
                    updateStatusFromSSE(status);
                } catch (e) {
                    throw e;
                }
            });
            
            eventSource.addEventListener('error', function(event) {
                eventSource.close();
                // 3秒后重新连接
                setTimeout(connectEventSource, 3000);
            });
        }

        // 根据SSE更新播放状态
        function updateStatusFromSSE(status) {
            console.log(status)

            // 更新播放时间和进度
            if (status.currentTime && status.duration) {
                const timeDisplay = document.getElementById('timeDisplay');
                const progress = document.getElementById('progress');
                
                if (timeDisplay && progress) {
                    const currentTimeStr = formatTime(status.currentTime);
                    const totalTimeStr = formatTime(status.duration);
                    timeDisplay.textContent = `${currentTimeStr} / ${totalTimeStr}`;
                    
                    // 计算并更新进度条
                    const progressPercent = (status.currentTime / status.duration) * 100;
                    progress.style.width = `${progressPercent}%`;
                    
                    // 更新全局变量
                    currentTime = status.currentTime;
                    totalTime = status.duration;
                }
            }
            
            // 检查是否播放完成 (status为stopped且currentFile为空)
            if (status.status === "stopped" && (!status.currentFile || status.currentFile === "")) {
                console.log("=================111")
                // 如果当前有文件在播放，说明是播放完成了，尝试播放下一曲
                const currentPlayingFile = document.getElementById("nowPlaying").textContent;
                if (currentPlayingFile && currentPlayingFile !== "未播放") {
                    
                    // 第一步：先将进度条设置为100%，表示当前歌曲已播放完毕
                    const progress = document.getElementById('progress');
                    const timeDisplay = document.getElementById('timeDisplay');
                    
                    if (progress && timeDisplay && totalTime > 0) {
                        // 1. 先设置为100%
                        progress.style.width = '100%';
                        timeDisplay.textContent = `${formatTime(totalTime)} / ${formatTime(totalTime)}`;
                        
                        // 2. 延时1000ms后重置为0%
                        setTimeout(() => {
                            progress.style.width = '0%';
                            timeDisplay.textContent = `00:00 / ${formatTime(totalTime)}`;
                            
                            // 3. 再延时1000ms播放下一曲
                            setTimeout(playNextTrack, 1000);
                        }, 1000);
                    } else {
                        // 如果进度条元素不存在或总时长为0，直接延时1000ms播放下一曲
                        setTimeout(playNextTrack, 1000);
                    }
                    return;
                }
            }

            console.log("=================112")
            // 更新播放状态显示
            if (status.status) {
                // 更新当前播放的文件
                if (status.currentFile) {
                    document.getElementById('nowPlaying').textContent = status.currentFile;
                    document.querySelector('.now-playing').classList.remove('hidden');
                } else if (status.status === "stopped") {
                    // 停止状态且没有文件名，更新为未播放
                    progress.style.width = '0%';
                    document.getElementById('nowPlaying').textContent = "未播放";
                }
                
                // 更新播放/暂停按钮状态
                const playBtn = document.getElementById('playBtn');
                const pauseBtn = document.getElementById('pauseBtn');
                
                if (status.status === 'playing') {
                    isPlaying = true;
                    playBtn.style.display = 'none';
                    pauseBtn.style.display = 'inline-block';
                } else if (status.status === 'paused') {
                    isPlaying = false;
                    playBtn.style.display = 'inline-block';
                    pauseBtn.style.display = 'none';
                } else {
                    isPlaying = false;
                    playBtn.style.display = 'inline-block';
                    pauseBtn.style.display = 'none';
                }
                
                // 更新播放列表高亮显示
                if (status.currentFile) {
                    updateActivePlaylistItem(status.currentFile);
                } else {
                    // 清除所有播放列表项的高亮和图标状态
                    document.querySelectorAll('.playlist-item').forEach(item => {
                        item.classList.remove('active');
                        const icon = item.querySelector('.play-icon');
                        if (icon) {
                            icon.classList.remove('playing', 'paused');
                            icon.innerHTML = '<i class="fas fa-play"></i>';
                        }
                    });
                }
            }
        }

        // 页面加载时检查用户信息并加载文件列表
        document.addEventListener('DOMContentLoaded', function() {
            const username = localStorage.getItem('username');
            const userRole = localStorage.getItem('userRole');
            
            if (!username || !userRole) {
                window.location.href = '/login.html';
                return;
            }
            
            // 根据用户角色显示/隐藏配置入口
            if (userRole === 'admin') {
                document.getElementById('configLink').style.display = 'block';
            }

            // 加载文件列表
            loadFileList();
            
            // 连接SSE获取实时播放状态
            connectEventSource();
            
            // 添加刷新按钮事件监听
            const refreshBtn = document.getElementById('refreshBtn');
            if (refreshBtn) {
                // 移除可能存在的旧事件监听器
                refreshBtn.removeEventListener('click', loadFileList);
                // 添加新的事件监听器
                refreshBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    loadFileList();
                });
            }
            
            // 添加全部删除按钮事件监听
            const deleteAllBtn = document.getElementById('deleteAllBtn');
            if (deleteAllBtn) {
                deleteAllBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    deleteAllFiles();
                });
            }
            
            // 添加到播放列表按钮事件监听
            const addToPlaylistBtn = document.getElementById('addToPlaylistBtn');
            if (addToPlaylistBtn) {
                addToPlaylistBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    addSelectedToPlaylist();
                });
            }
            
            // 清空播放列表按钮事件监听
            const clearPlaylistBtn = document.getElementById('clearPlaylistBtn');
            if (clearPlaylistBtn) {
                clearPlaylistBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    clearPlaylist();
                });
            }
            
            // 从localStorage加载播放列表
            loadPlaylist();

            // 检查所有按钮样式一致性
            const buttons = document.querySelectorAll('button:not(.btn)');
            buttons.forEach(button => {
                button.classList.add('btn');
            });
        });

        // 加载文件列表
        function loadFileList() {
            // 获取之前选中的文件
            const selectedFiles = JSON.parse(localStorage.getItem('selectedAudioFiles') || '[]');
            
            // 获取当前播放的文件名
            const currentPlayingFile = document.getElementById('nowPlaying').textContent;

            // 添加时间戳防止缓存
            const timestamp = new Date().getTime();
            fetch(`/api/music/list?_=${timestamp}`, {
                method: 'GET',
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0',
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`网络响应不正常: ${response.status}`);
                }
                return response.json().catch(error => {
                    throw new Error('服务器响应格式错误');
                });
            })
            .then(data => {
                // 使用隐藏变量存储文件总数和已选数量，而不是更新DOM元素
                window.totalFiles = data.total || 0;
                window.selectedFiles = 0;
                
                // 更新存储信息
                if (data.storage) {
                    document.getElementById('storageInfo').textContent = 
                        `${formatFileSize(data.storage.used)}/${formatFileSize(data.storage.total)}`;
                }

                // 清空文件列表
                const fileList = document.getElementById('fileList');
                fileList.innerHTML = '';

                // 添加文件到列表
                if (data.files && data.files.length > 0) {
                    // 获取当前播放列表
                    const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
                    
                    // 如果播放列表非空，按播放列表顺序排序
                    if (playlist.length > 0) {
                        // 创建一个新的排序后的文件数组
                        const sortedFiles = [];
                        
                        // 先添加播放列表中的文件，按播放列表顺序
                        playlist.forEach(playlistFilename => {
                            const matchingFile = data.files.find(file => file.name === playlistFilename);
                            if (matchingFile) {
                                sortedFiles.push(matchingFile);
                            }
                        });
                        
                        // 再添加不在播放列表中的文件，按文件名升序排序
                        const remainingFiles = data.files.filter(file => !playlist.includes(file.name));
                        remainingFiles.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
                        
                        // 合并两个数组
                        data.files = [...sortedFiles, ...remainingFiles];
                    } else {
                        // 播放列表为空，按默认的文件名升序排序
                        data.files.sort((a, b) => {
                            return a.name.localeCompare(b.name, 'zh-CN');
                        });
                    }
                    
                    data.files.forEach((file, index) => {
                        const li = document.createElement('div');
                        li.className = 'audio-item';
                        
                        // 检查此文件是否之前被选中
                        const isSelected = selectedFiles.includes(file.name);
                        
                        // 检查文件是否在播放列表中
                        const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
                        const isInPlaylist = playlist.includes(file.name);
                        const disabledClass = isInPlaylist ? 'disabled-btn' : '';
                        
                        // 如果在播放列表中，添加特殊样式
                        if (isInPlaylist) {
                            li.classList.add('in-playlist');
                        }

                        li.innerHTML = `
                            <button class="play-file-btn ${disabledClass}" onclick="${isInPlaylist ? 'showFileInPlaylistAlert' : 'addToPlaylist'}('${file.name}')">
                                <i class="fas fa-arrow-left"></i>
                            </button>
                            <input type="checkbox" class="audio-checkbox" ${isSelected ? 'checked' : ''}>
                            <span class="filename">${file.name}</span>
                            <span class="file-size">${formatFileSize(file.size)}</span>
                            <button class="delete-btn ${disabledClass}" onclick="${isInPlaylist ? 'showFileInPlaylistAlert' : 'deleteFile'}('${file.name}')">
                                <i class="fas fa-trash"></i>
                            </button>
                        `;
                        fileList.appendChild(li);
                    });

                    // 添加复选框事件监听
                    document.querySelectorAll('.audio-checkbox').forEach(checkbox => {
                        checkbox.addEventListener('change', function() {
                            updateSelectedCount();
                            saveSelectedFiles();
                        });
                    });
                } else {
                    fileList.innerHTML = '<div class="audio-item">没有音频文件</div>';
                }
                
                // 更新选中计数
                updateSelectedCount();
                
                // 更新音频文件的播放图标状态
                updateAudioPlayIcons();
            })
            .catch(error => {
                showAlert('操作提示', '加载文件列表失败: ' + error.message);
                
                // 显示错误状态
                const fileList = document.getElementById('fileList');
                fileList.innerHTML = `<div class="audio-item" style="color: red;">加载失败: ${error.message}</div>`;
            });
        }

        // 保存选中的文件到localStorage
        function saveSelectedFiles() {
            const selectedFiles = [];
            document.querySelectorAll('.audio-checkbox:checked').forEach(checkbox => {
                const filename = checkbox.closest('.audio-item').querySelector('.filename').textContent;
                selectedFiles.push(filename);
            });
            localStorage.setItem('selectedAudioFiles', JSON.stringify(selectedFiles));
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 更新选中计数
        function updateSelectedCount() {
            const selectedCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
            
            // 更新内部变量
            window.selectedFiles = selectedCount;
            
            // 显示或隐藏添加到播放列表按钮
            const addToPlaylistBtn = document.getElementById('addToPlaylistBtn');
            if (addToPlaylistBtn) {
                addToPlaylistBtn.style.display = selectedCount > 0 ? 'flex' : 'none';
            }
        }

        // 播放控制
        const playBtn = document.getElementById('playBtn');
        const pauseBtn = document.getElementById('pauseBtn');
        const progress = document.getElementById('progress');
        const timeDisplay = document.getElementById('timeDisplay');
        let isPlaying = false;

        // 播放相关变量
        let currentTime = 0;
        let totalTime = 0; // 由SSE提供实际值

        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        }

        const stopBtn = document.getElementById('stopBtn');
        const nowPlaying = document.getElementById('nowPlaying');
        let pausedTime = 0;

        // 获取播放列表中的下一首歌
        function getNextTrack(currentTrack) {
            const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            if (playlist.length === 0) return null;
            
            const currentIndex = playlist.indexOf(currentTrack);
            // 如果当前歌曲不在列表中或是最后一首，从第一首开始播放
            if (currentIndex === -1 || currentIndex === playlist.length - 1) {
                return playlist[0];
            }
            
            // 返回下一首歌
            return playlist[currentIndex + 1];
        }

        // 播放下一曲
        function playNextTrack() {
            const currentTrack = nowPlaying.textContent;
            if (currentTrack === '未播放') {
                // 当前没有播放任何歌曲，从列表第一首开始播放
                const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
                if (playlist.length > 0) {
                    playFile(playlist[0]);
                } else {
                    showAlert('操作提示', '播放列表为空，请先添加歌曲');
                }
                return;
            }
            
            const nextTrack = getNextTrack(currentTrack);
            if (nextTrack) {
                playFile(nextTrack);
            } else {
                // 如果没有下一首，停止播放
                stopPlayback();
            }
        }

        // 播放指定文件
        function playFile(filename) {
            if (isPlaying && nowPlaying.textContent === filename) {
                // 如果当前正在播放该文件，则暂停
                pausePlayback();
                return;
            }
            
            // 检查是否是当前暂停的文件
            const isPausedCurrentFile = !isPlaying && nowPlaying.textContent === filename && pausedTime > 0;
            
            // 向后端发送播放请求，如果是暂停状态继续播放则使用resume
            let action = isPausedCurrentFile ? 'resume' : 'play';
            
            fetch(`/api/music/control?action=${action}&filename=${encodeURIComponent(filename)}`, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 400 && action === 'resume') {
                        // 如果是恢复播放失败（400错误），尝试使用play action重新播放
                        console.log('恢复播放失败，尝试重新播放');
                        return fetch(`/api/music/control?action=play&filename=${encodeURIComponent(filename)}`, {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json'
                            }
                        });
                    } else {
                        // 其他错误，抛出异常
                        throw new Error(`HTTP错误 ${response.status}: ${response.statusText}`);
                    }
                }
                return response.json();
            })
            .then(data => {
                console.log('播放操作结果:', data);
            })
            .catch(error => {
                console.error('播放请求出错:', error);
                // 出错时重置UI状态
                if (nowPlaying.textContent === filename) {
                    isPlaying = false;
                    window.isPlaying = false;
                    playBtn.style.display = 'inline-block';
                    pauseBtn.style.display = 'none';
                }
            });

            isPlaying = true;
            window.isPlaying = true;
            playBtn.style.display = 'none';
            pauseBtn.style.display = 'inline-block';
            
            // 显示正在播放的文件名
            nowPlaying.textContent = filename;
            
            // 更新播放列表中的活动项
            updateActivePlaylistItem(filename);
            
            // 更新音频文件的播放图标
            updateAudioPlayIcons();
            
            // 设置计时 - 如果是暂停状态继续，使用已保存的时间点
            if (!isPausedCurrentFile) {
                // 新文件，重置计时
                currentTime = 0;
                pausedTime = 0;
            } else {
                // 从暂停状态继续，使用已保存的时间点
                currentTime = pausedTime;
            }
        }
        
        // 更新播放列表中活动项的状态
        function updateActivePlaylistItem(filename) {
            // 移除所有项的活动状态
            document.querySelectorAll('.playlist-item').forEach(item => {
                item.classList.remove('active');
                const icon = item.querySelector('.play-icon');
                if (icon) {
                    icon.classList.remove('playing', 'paused');
                    icon.innerHTML = '<i class="fas fa-play"></i>';
                }
            });
            
            // 为当前播放的项添加活动状态 - 使用更精确的选择器
            document.querySelectorAll('.playlist-item').forEach(item => {
                const itemFilename = item.getAttribute('data-filename');
                if (itemFilename === filename) {
                    item.classList.add('active');
                    const icon = item.querySelector('.play-icon');
                    if (icon) {
                        if (isPlaying) {
                            icon.classList.add('playing');
                            icon.innerHTML = '<i class="fas fa-play"></i>';
                        } else {
                            icon.classList.add('paused');
                            icon.innerHTML = '<i class="fas fa-pause"></i>';
                        }
                    }
                }
            });
            
            // 确保播放列表项可见（滚动到视图）
            const activeItem = document.querySelector('.playlist-item.active');
            if (activeItem) {
                activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        }
        
        // 主播放按钮负责继续播放当前文件或从播放列表开始播放
        function startPlayback() {
            const currentFile = nowPlaying.textContent;
            if (currentFile === '未播放') {
                // 没有正在播放的文件，从播放列表开始播放
                playNextTrack();
                return;
            }
            
            // 检查是否是从暂停状态继续播放
            const isResuming = pausedTime > 0;
            
            // 向后端发送播放请求
            console.log('开始播放', isResuming ? 'resume' : 'play', currentFile);
            fetch(`/api/music/control?action=${isResuming ? 'resume' : 'play'}&filename=${encodeURIComponent(currentFile)}`, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .catch(error => {
                throw error;
            });

            isPlaying = true;
            window.isPlaying = true;
            playBtn.style.display = 'none';
            pauseBtn.style.display = 'inline-block';
            
            // 如果是从暂停状态继续播放，使用暂停时的时间
            if (isResuming) {
                currentTime = pausedTime;
            } else {
                // 否则从头开始
                currentTime = 0;
            }
            
            // 重新加载播放列表以确保UI状态一致
            loadPlaylist();
            
            // 更新音频文件的播放图标
            updateAudioPlayIcons();
        }
        
        function pausePlayback() {
            // 获取当前播放的文件名
            const currentFile = document.getElementById('nowPlaying').textContent;
            if (currentFile !== '未播放') {
                
                // 向后端发送暂停请求
                fetch('/api/music/control?action=pause', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .catch(error => {
                    throw error;
                });
            }

            isPlaying = false;
            window.isPlaying = false; // 更新全局状态
            playBtn.style.display = 'inline-block';
            pauseBtn.style.display = 'none';
            pausedTime = currentTime; // 记住暂停时的时间点
            
            // 重新加载播放列表以更新UI状态
            loadPlaylist();
            
            // 更新音频文件的播放图标
            updateAudioPlayIcons();
        }

        function stopPlayback() {
            // 获取当前播放的文件名
            const currentFile = document.getElementById('nowPlaying').textContent;
            if (currentFile !== '未播放') {
                
                // 向后端发送停止请求
                fetch('/api/music/control?action=stop', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .catch(error => {
                    throw error;
                });
            }

            isPlaying = false;
            window.isPlaying = false; // 更新全局状态
            playBtn.style.display = 'inline-block';
            pauseBtn.style.display = 'none';
            currentTime = 0;
            pausedTime = 0; // 清除暂停时间点
            progress.style.width = '0%';
            timeDisplay.textContent = '00:00 / 00:00';
            
            // 先保存当前文件名，然后更新显示
            const previousFile = nowPlaying.textContent;
            nowPlaying.textContent = '未播放';
            
            // 清除播放列表中的所有活动状态
            document.querySelectorAll('.playlist-item').forEach(item => {
                item.classList.remove('active');
                const icon = item.querySelector('.play-icon');
                if (icon) {
                    icon.classList.remove('playing', 'paused');
                    icon.innerHTML = '<i class="fas fa-play"></i>';
                }
            });
            
            // 更新音频文件的播放图标
            updateAudioPlayIcons();
        }

        playBtn.addEventListener('click', startPlayback);
        pauseBtn.addEventListener('click', pausePlayback);
        stopBtn.addEventListener('click', stopPlayback);

        // 进度条点击
        document.querySelector('.progress-bar').addEventListener('click', function(e) {
            if (!isPlaying) return;
            const rect = this.getBoundingClientRect();
            const percent = (e.clientX - rect.left) / rect.width;
            currentTime = Math.floor(percent * totalTime);
            progress.style.width = `${percent * 100}%`;
            timeDisplay.textContent = `${formatTime(currentTime)} / ${formatTime(totalTime)}`;
        });

        // 文件上传处理
        const fileInput = document.getElementById('fileUpload');
        const uploadStatus = document.getElementById('uploadStatus');

        function handleFileUpload(files) {
            if (files.length === 0) return;

            const formData = new FormData();
            let totalSize = 0;
            let fileCount = 0;
            for (const file of files) {
                formData.append('files[]', file);
                totalSize += file.size;
                fileCount++;
            }

            // 显示上传进度弹框
            const modal = document.getElementById('uploadModal');
            const progressBar = document.getElementById('uploadProgress');
            const progressText = document.getElementById('uploadStatus');
            const progressPercent = document.getElementById('uploadPercent');
            const uploadSummary = document.getElementById('uploadSummary');
            const uploadRefreshTip = document.getElementById('uploadRefreshTip');
            const modalFooter = document.getElementById('uploadModalFooter');
            const closeBtn = document.getElementById('uploadCloseBtn');
            
            // 重置模态框状态
            modal.style.display = 'flex';
            progressBar.style.width = '0%';
            progressBar.style.backgroundColor = '#4CAF50';
            uploadSummary.style.display = 'none';
            uploadRefreshTip.style.display = 'none';
            modalFooter.style.display = 'none';
            document.getElementById('uploadTitle').textContent = '文件上传中';
            const modalContent = modal.querySelector('.modal-content');
            modalContent.classList.remove('success', 'error');

            // 添加关闭按钮事件
            closeBtn.onclick = function() {
                modal.style.display = 'none';
                loadFileList(); // 再次刷新列表确保显示最新状态
            };

            // 发送上传请求
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/api/music/upload', true);

            // 进度处理
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percent + '%';
                    progressPercent.textContent = percent + '%';
                    progressText.textContent = `已上传 ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)}`;
                    
                    // 计算上传速度
                    const currentTime = new Date().getTime();
                    if (!window.uploadStartTime) {
                        window.uploadStartTime = currentTime;
                        window.uploadLastBytes = 0;
                    }
                    
                    const elapsedTime = (currentTime - window.uploadStartTime) / 1000; // 秒
                    if (elapsedTime > 0) {
                        const bytesPerSecond = e.loaded / elapsedTime;
                        const speed = formatFileSize(bytesPerSecond) + '/s';
                        
                        // 更新状态显示，包括速度
                        const remaining = (e.total - e.loaded) / bytesPerSecond;
                        const remainingText = remaining > 1 ? 
                            `预计剩余 ${Math.round(remaining)}秒` : 
                            '即将完成';
                        
                        document.getElementById('uploadStatus').textContent = 
                            `已上传 ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)} (${speed}, ${remainingText})`;
                    }
                }
            };

            // 上传完成处理
            xhr.onload = function() {
                const modalContent = modal.querySelector('.modal-content');
                const uploadTitle = document.getElementById('uploadTitle');
                window.uploadStartTime = null; // 重置上传时间
                
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        progressBar.style.width = '100%';
                        uploadTitle.textContent = '上传成功';
                        
                        // 添加成功摘要信息
                        uploadSummary.innerHTML = `成功上传 <strong>${fileCount}</strong> 个文件，共 <strong>${formatFileSize(totalSize)}</strong>`;
                        uploadSummary.style.display = 'block';
                        uploadRefreshTip.style.display = 'block';
                        
                        modalContent.classList.add('success');
                        modalFooter.style.display = 'block';
                        
                        // 自动刷新文件列表
                        loadFileList();
                    } catch (e) {
                        uploadTitle.textContent = '上传成功，但解析响应失败';
                        modalContent.classList.add('error');
                    }
                } else {
                    let errorMsg = '上传失败';
                    try {
                        const response = JSON.parse(xhr.responseText);
                        errorMsg = response.error || errorMsg;
                    } catch (e) {}
                    uploadTitle.textContent = '上传失败';
                    progressText.textContent = errorMsg;
                    progressBar.style.backgroundColor = '#f44336';
                    modalContent.classList.add('error');
                    modalFooter.style.display = 'block';
                }
            };

            // 错误处理
            xhr.onerror = function() {
                const modalContent = modal.querySelector('.modal-content');
                const uploadTitle = document.getElementById('uploadTitle');
                uploadTitle.textContent = '上传失败';
                progressText.textContent = '网络错误，上传失败';
                progressBar.style.backgroundColor = '#f44336';
                modalContent.classList.add('error');
                modalFooter.style.display = 'block';
                window.uploadStartTime = null; // 重置上传时间
            };

            // 开始上传
            window.uploadStartTime = new Date().getTime();
            xhr.send(formData);
        }

        fileInput.addEventListener('change', function(e) {
            handleFileUpload(this.files);
            this.value = ''; // 清空输入，允许重复选择同一文件
        });

        // 文件拖放处理
        const dropZone = document.querySelector('.audio-list-container');
        
        dropZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('dragover');
        });

        dropZone.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
        });

        dropZone.addEventListener('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
            handleFileUpload(e.dataTransfer.files);
        });

        // 全部删除文件
        function deleteAllFiles() {
            // 检查是否有文件正在播放列表中
            const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            
            if (playlist.length > 0) {
                showAlert('操作提示', '有文件在播放列表中，请先清空播放列表');
                return;
            }
            
            if (!confirm('确定要删除所有音频文件吗？此操作不可恢复！')) {
                return;
            }
            
            // 发送删除所有文件的请求 - 尝试不设置Content-Type和请求体
            fetch('/api/music/delete/all', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showAlert('操作提示', `成功删除所有音频文件（共 ${data.count || 0} 个文件）`);
                    // 刷新文件列表
                    setTimeout(() => {
                        loadFileList();
                    }, 500);
                } else {
                    showAlert('操作提示', data.error || '删除失败');
                }
            })
            .catch(error => {
                showAlert('操作提示', '全部删除失败: ' + error.message);
                // 即使出错也尝试刷新列表
                setTimeout(() => {
                    loadFileList();
                }, 1000);
            });
        }

        // 添加选中文件到播放列表
        function addSelectedToPlaylist() {
            const checkedItems = document.querySelectorAll('.audio-checkbox:checked');
            if (checkedItems.length === 0) {
                showAlert('操作提示', '请选择要添加到播放列表的文件');
                return;
            }
            
            // 获取当前播放列表
            let playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            let addedCount = 0;
            let pendingAdds = [];
            
            // 收集要添加的文件
            checkedItems.forEach(checkbox => {
                const filename = checkbox.closest('.audio-item').querySelector('.filename').textContent;
                
                // 检查是否已在播放列表中
                if (!playlist.includes(filename)) {
                    // 构建播放列表项数据
                    const audioItem = {
                        name: filename,
                        path: `/audio/${filename}`,
                        format: getAudioFormat(filename),
                        id: generateUniqueID(),
                        addedAt: new Date().toISOString()
                    };
                    
                    pendingAdds.push({ filename, item: audioItem });
                }
                
                // 无论是否添加成功，都取消勾选
                checkbox.checked = false;
            });
            
            // 如果没有需要添加的项
            if (pendingAdds.length === 0) {
                showAlert('操作提示', '所选文件已在播放列表中');
                
                // 清空localStorage中的选中文件记录
                localStorage.setItem('selectedAudioFiles', JSON.stringify([]));
                
                // 更新选中计数
                updateSelectedCount();
                return;
            }
            
            // 逐个添加到服务器
            const addItemPromises = pendingAdds.map(({ filename, item }) => {
                return fetch('/api/music/playlists/default/items', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(item)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`服务器响应错误: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 添加成功计数
                        addedCount++;
                        // 添加到本地播放列表
                        if (!playlist.includes(filename)) {
                            playlist.push(filename);
                        }
                        // 更新该文件的按钮状态为禁用
                        updateFileButtonsStatus(filename, true);
                        return true;
                    } else {
                        return false;
                    }
                })
                .catch(error => {
                    return false;
                });
            });
            
            // 等待所有添加操作完成
            Promise.all(addItemPromises)
            .then(results => {
                // 保存播放列表到localStorage
                localStorage.setItem('audioPlaylist', JSON.stringify(playlist));
                
                // 清空localStorage中的选中文件记录
                localStorage.setItem('selectedAudioFiles', JSON.stringify([]));
                
                // 刷新播放列表显示
                loadPlaylist();
                
                // 刷新文件列表，确保按照播放列表顺序显示
                loadFileList();
                
                // 显示消息
                if (addedCount > 0) {
                    showAlert('操作提示', `已添加 ${addedCount} 个文件到播放列表`);
                } else {
                    showAlert('操作提示', '添加失败，请稍后再试');
                }
                
                // 更新选中计数
                updateSelectedCount();
            });
        }
        
        // 从播放列表中移除文件
        function removeFromPlaylist(filename, itemId) {
            // 检查是否有文件正在播放或暂停状态
            const currentPlayingFile = document.getElementById('nowPlaying').textContent;
            
            // 只要有文件处于"未播放"以外的状态(播放中或暂停状态)，都不能移除
            if (currentPlayingFile !== '未播放') {
                showAlert('操作提示', '请先停止播放再从播放列表中移除文件');
                return;
            }
            
            // 获取当前播放列表
            let playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            
            // 如果传入了itemId，直接使用该ID删除
            if (itemId) {
                deletePlaylistItem(itemId, filename, playlist);
                return;
            }
            
            // 如果没有传入ID，尝试从DOM元素获取ID
            const playlistItem = document.querySelector(`.playlist-item[data-filename="${filename}"]`);
            if (playlistItem) {
                const itemIdFromDOM = playlistItem.getAttribute('data-id');
                if (itemIdFromDOM) {
                    deletePlaylistItem(itemIdFromDOM, filename, playlist);
                    return;
                }
            }
            
            // 如果还是没有找到ID，尝试从服务器获取
            // 先尝试从服务器获取默认播放列表以查找项ID
            fetch('/api/music/playlists/default', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 获取播放列表数据
                const playlistData = data.playlist || {};
                const playlistItems = playlistData.items || [];
                
                // 查找对应文件名的项
                const item = playlistItems.find(item => item.name === filename);
                if (!item) {
                    throw new Error('播放列表中未找到该项');
                }
                
                const foundItemId = item.id;
                
                deletePlaylistItem(foundItemId, filename, playlist);
            })
            .catch(error => {
                showAlert('操作提示', '从播放列表移除失败: ' + error.message);
                
                // 如果服务器出错，尝试使用本地方法移除
                const index = playlist.indexOf(filename);
                if (index > -1) {
                    playlist.splice(index, 1);
                    localStorage.setItem('audioPlaylist', JSON.stringify(playlist));
                    
                    // 更新文件列表项按钮状态
                    updateFileButtonsStatus(filename, false);
                    
                    // 刷新播放列表显示
                    loadPlaylist();
                    
                    // 刷新文件列表，确保文件状态和样式正确更新
                    loadFileList();
                }
            });
        }
        
        // 清空播放列表
        function clearPlaylist() {
            // 检查是否有文件正在播放或暂停状态
            const currentPlayingFile = document.getElementById('nowPlaying').textContent;
            
            // 只要有文件处于"未播放"以外的状态(播放中或暂停状态)，都不能清空
            if (currentPlayingFile !== '未播放') {
                showAlert('操作提示', '请先停止播放再清空播放列表');
                return;
            }
            
            if (!confirm('确定要清空播放列表吗？')) {
                return;
            }
            
            // 获取当前播放列表中的所有文件
            const currentPlaylist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            
            // 向服务器发送清空请求
            fetch('/api/music/playlists/default/clear', {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 清空本地播放列表
                    localStorage.setItem('audioPlaylist', JSON.stringify([]));
                    
                    // 恢复所有文件的按钮状态
                    currentPlaylist.forEach(filename => {
                        updateFileButtonsStatus(filename, false);
                    });
                    
                    // 刷新播放列表显示
                    loadPlaylist();
                    
                    // 刷新文件列表，确保文件状态和样式正确更新
                    loadFileList();
                } else {
                    showAlert('操作提示', data.error || '清空播放列表失败');
                }
            })
            .catch(error => {
                showAlert('操作提示', '清空播放列表失败: ' + error.message);
            });
        }
        
        // 加载播放列表
        function loadPlaylist() {
            // 获取播放列表容器
            const playlistContainer = document.getElementById('playlist');
            // 先尝试从服务器获取默认播放列表
            fetch('/api/music/playlists/default', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.text().then(text => {
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        throw new Error("解析服务器响应失败");
                    }
                });
            })
            .then(data => {
                // 清空播放列表容器
                playlistContainer.innerHTML = '';
                
                // 获取播放列表数据
                const playlistData = data.playlist || {};
                const playlistItems = playlistData.items || [];
                
                // 获取当前播放的文件
                const currentPlayingFile = document.getElementById('nowPlaying').textContent;
                
                // 如果播放列表为空
                if (playlistItems.length === 0) {
                    playlistContainer.innerHTML = '<div class="playlist-empty">播放列表为空</div>';
                    
                    // 清空本地存储的播放列表
                    localStorage.setItem('audioPlaylist', JSON.stringify([]));
                    return;
                }
                
                // 保存到本地缓存，以便其他函数使用
                const fileNames = playlistItems.map(item => item.name);
                localStorage.setItem('audioPlaylist', JSON.stringify(fileNames));
                
                // 添加文件到播放列表
                playlistItems.forEach((item, index) => {
                    const filename = item.name;
                    const itemId = item.id; // 记住每一项的id
                    const listItem = document.createElement('div');
                    listItem.className = 'playlist-item';
                    listItem.setAttribute('data-filename', filename);
                    listItem.setAttribute('data-id', itemId); // 存储ID到DOM元素
                    
                    // 设置适当的播放图标类和内容
                    let iconClass = '';
                    let iconHTML = '<i class="fas fa-play"></i>';
                    
                    if (filename === currentPlayingFile) {
                        // 添加激活状态类
                        listItem.classList.add('active');
                        
                        if (isPlaying) {
                            iconClass = 'playing';
                        } else {
                            iconClass = 'paused';
                            iconHTML = '<i class="fas fa-pause"></i>';
                        }
                    }
                    
                    listItem.innerHTML = `
                        <div class="playlist-filename" onclick="playFile('${filename}')">${filename}</div>
                        <div class="play-icon ${iconClass}" onclick="playFile('${filename}')">
                            ${iconHTML}
                        </div>
                        <button class="remove-btn" onclick="removeFromPlaylist('${filename}', '${itemId}'); event.stopPropagation();">
                            <i class="fas fa-arrow-right"></i>
                        </button>
                    `;
                    
                    playlistContainer.appendChild(listItem);
                });
            })
            .catch(error => {
                showAlert('操作提示', '获取播放列表失败，使用本地缓存: ' + error.message);
                
                // 获取失败时使用本地存储的播放列表
                fallbackToLocalPlaylist();
            });
        }

        // 回退到本地存储的播放列表
        function fallbackToLocalPlaylist() {
            // 获取播放列表容器
            const playlistContainer = document.getElementById('playlist');
            
            // 获取当前播放列表
            const playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            
            // 获取当前播放的文件
            const currentPlayingFile = document.getElementById('nowPlaying').textContent;
            
            // 清空播放列表容器
            playlistContainer.innerHTML = '';
            
            // 如果播放列表为空
            if (playlist.length === 0) {
                playlistContainer.innerHTML = '<div class="playlist-empty">播放列表为空</div>';
                return;
            }
            
            // 添加文件到播放列表
            playlist.forEach((filename, index) => {
                const item = document.createElement('div');
                item.className = 'playlist-item';
                item.setAttribute('data-filename', filename);
                
                // 设置适当的播放图标类和内容
                let iconClass = '';
                let iconHTML = '<i class="fas fa-play"></i>';
                
                if (filename === currentPlayingFile) {
                    // 添加激活状态类
                    item.classList.add('active');
                    
                    if (isPlaying) {
                        iconClass = 'playing';
                    } else {
                        iconClass = 'paused';
                        iconHTML = '<i class="fas fa-pause"></i>';
                    }
                }
                
                item.innerHTML = `
                    <div class="playlist-filename" onclick="playFile('${filename}')">${filename}</div>
                    <div class="play-icon ${iconClass}" onclick="playFile('${filename}')">
                        ${iconHTML}
                    </div>
                    <button class="remove-btn" onclick="removeFromPlaylist('${filename}'); event.stopPropagation();">
                        <i class="fas fa-arrow-right"></i>
                    </button>
                `;
                
                playlistContainer.appendChild(item);
            });
        }

        // 实际删除播放列表项的函数
        function deletePlaylistItem(itemId, filename, playlist) {
            // 向服务器发送删除请求
            fetch(`/api/music/playlists/default/items/${itemId}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.text().then(text => {
                    try {
                        return text ? JSON.parse(text) : {};
                    } catch (e) {
                        throw new Error("解析服务器响应失败");
                    }
                });
            })
            .then(data => {
                if (data.success) {
                    // 从本地播放列表中移除
                    const index = playlist.indexOf(filename);
                    if (index > -1) {
                        playlist.splice(index, 1);
                    }
                    localStorage.setItem('audioPlaylist', JSON.stringify(playlist));
                    
                    // 更新文件列表项按钮状态
                    updateFileButtonsStatus(filename, false);
                    
                    // 刷新播放列表显示
                    loadPlaylist();
                    
                    // 刷新文件列表，确保文件状态和样式正确更新
                    loadFileList();
                } else {
                    showAlert('操作提示', data.error || '从播放列表移除失败');
                }
            })
            .catch(error => {
                showAlert('操作提示', '从播放列表移除失败: ' + error.message);
            });
        }

        // 向播放列表添加单个文件
        function addToPlaylist(filename) {
            // 获取当前播放列表
            let playlist = JSON.parse(localStorage.getItem('audioPlaylist') || '[]');
            
            // 检查是否已在播放列表中
            if (playlist.includes(filename)) {
                return;
            }
            
            // 构建播放列表项数据 - 注意使用小写字段名
            const audioItem = {
                name: filename,
                path: `/audio/${filename}`,
                format: getAudioFormat(filename),
                id: generateUniqueID(),
                addedAt: new Date().toISOString()
            };
            
            // 向服务器添加到默认播放列表
            fetch('/api/music/playlists/default/items', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(audioItem)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                return response.text().then(text => {
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        throw new Error("解析服务器响应失败");
                    }
                });
            })
            .then(data => {
                if (data.success) {
                    // 添加到本地播放列表
                    playlist.push(filename);
                    localStorage.setItem('audioPlaylist', JSON.stringify(playlist));

                    // 刷新播放列表显示
                    loadPlaylist();
                    
                    // 更新文件列表项按钮状态
                    updateFileButtonsStatus(filename, true);
                    
                    // 刷新文件列表，确保按播放列表顺序排序
                    loadFileList();
                } else {
                    showAlert('操作提示', data.error || '添加到播放列表失败');
                }
            })
            .catch(error => {
                showAlert('操作提示', '添加到播放列表失败: ' + error.message);
            });
        }

        // 更新音频文件的播放图标状态
        function updateAudioPlayIcons() {
            // 重置所有图标状态为默认（灰色）并移除激活状态
            document.querySelectorAll('.playlist-item').forEach(item => {
                item.classList.remove('active');
                const icon = item.querySelector('.play-icon');
                if (icon) {
                    icon.classList.remove('playing', 'paused');
                    icon.innerHTML = '<i class="fas fa-play"></i>';
                }
            });
            
            // 获取当前播放文件和状态
            const currentFile = document.getElementById('nowPlaying').textContent;
            if (currentFile === '未播放') return;
            
            // 查找当前播放文件并设置状态
            document.querySelectorAll('.playlist-item').forEach(item => {
                const filename = item.getAttribute('data-filename');
                if (filename === currentFile) {
                    // 设置激活状态
                    item.classList.add('active');
                    
                    const icon = item.querySelector('.play-icon');
                    if (icon) {
                        if (isPlaying) {
                            icon.classList.add('playing');
                            icon.innerHTML = '<i class="fas fa-play"></i>';
                        } else {
                            icon.classList.add('paused');
                            icon.innerHTML = '<i class="fas fa-pause"></i>';
                        }
                    }
                }
            });
        }

        // 显示文件在播放列表中的提示
        function showFileInPlaylistAlert(filename) {
            showAlert('操作提示', `文件 "${filename}" 已在播放列表中，请先从播放列表中移除`);
        }

        // 更新文件列表中的按钮状态
        function updateFileButtonsStatus(filename, isInPlaylist) {
            const fileItems = document.querySelectorAll('.audio-item');
            fileItems.forEach(item => {
                const itemFilename = item.querySelector('.filename').textContent;
                if (itemFilename === filename) {
                    const deleteBtn = item.querySelector('.delete-btn');
                    const addBtn = item.querySelector('.play-file-btn');
                    
                    if (isInPlaylist) {
                        // 禁用按钮
                        deleteBtn.classList.add('disabled-btn');
                        addBtn.classList.add('disabled-btn');
                        deleteBtn.setAttribute('onclick', `showFileInPlaylistAlert('${filename}')`);
                        addBtn.setAttribute('onclick', `showFileInPlaylistAlert('${filename}')`);
                        // 添加播放列表项样式
                        item.classList.add('in-playlist');
                    } else {
                        // 启用按钮
                        deleteBtn.classList.remove('disabled-btn');
                        addBtn.classList.remove('disabled-btn');
                        deleteBtn.setAttribute('onclick', `deleteFile('${filename}')`);
                        addBtn.setAttribute('onclick', `addToPlaylist('${filename}')`);
                        // 移除播放列表项样式
                        item.classList.remove('in-playlist');
                    }
                }
            });
        }

        // 工具函数：获取音频格式
        function getAudioFormat(filename) {
            const ext = filename.split('.').pop().toLowerCase();
            switch (ext) {
                case 'mp3': return 'MP3';
                case 'wav': return 'WAV';
                case 'ogg': return 'OGG';
                case 'flac': return 'FLAC';
                default: return 'WAV';
            }
        }

        // 工具函数：生成唯一ID
        function generateUniqueID() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
        }
    </script>
</body>
</html>
